<!--
 * @Author: 橘子
 * @Date: 2022-10-24 10:25:32
 * @Project_description: pdf预览
 * @Description: 代码是我抄的，不会也是真的
-->
<template>
  <div>
    <el-dialog :visible.sync='dialogVisible' title='' width='70%'>
      <div>
        <el-button-group class='btns'>
          <el-button circle icon='el-icon-arrow-left' size='mini' @click='prePage'></el-button>
          <div style='margin: 0 30px; color: #999'>{{ pageNum }} / {{ pageTotalNum }}</div>
          <el-button circle icon='el-icon-arrow-right' size='mini' @click='nextPage'></el-button>
        </el-button-group>
        <pdf :page='pageNum' :src='url' @progress='loadedRatio = $event' @num-pages='pageTotalNum = $event'></pdf>
      </div>
      <span slot='footer' class='dialog-footer'>
        <el-button @click='dialogVisible = false'>取 消</el-button>
        <el-button type='primary' @click='dowloadFile(url)'>下载</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dowload from '@/libs/util.dowloadFile'
import { Message } from 'element-ui'
import pdf from 'vue-pdf'

export default {
  components: {
    pdf,
  },
  data() {
    return {
      url: '',
      numPages: null, // pdf 总页数
      dialogVisible: false,
      pageNum: 1, //当前
      pageTotalNum: 1, // 总页数
      loadedRatio: 0, //范围是0-1 ，等于1的时候代表当前页已经完全加载完成了
    }
  },
  mounted() {
  },
  methods: {
    init(url) {
      if (!url) return Message.error('pdf地址不存在')
      this.url = url
      this.getNumPages()
    },
    // 计算pdf页码总数
    getNumPages() {
      let loadingTask = pdf.createLoadingTask(this.url)
      loadingTask.promise
        .then((pdf) => {
          this.numPages = pdf.numPages
          this.dialogVisible = true
        })
        .catch((err) => {
          console.error('pdf加载失败', err)
          return Message.error('pdf加载失败')
        })
    },
    // 上一页
    prePage() {
      let page = this.pageNum
      page = page > 1 ? page - 1 : this.pageTotalNum
      this.pageNum = page
    },

    // 下一页
    nextPage() {
      let page = this.pageNum
      page = page < this.pageTotalNum ? page + 1 : 1
      this.pageNum = page
    },
    //下载
    dowloadFile(url) {
      dowload(url)
    },
  },
}
</script>

<style scoped>
.btns {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
